﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using PMSGSC.BLL;
using PMSGSC.DAL;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Localization;
using System.IO;
using DevExpress.XtraEditors.Controls;
using System.Data.Linq;
using PMSGSC.Common;
using System.Diagnostics;
using DevExpress.XtraRichEdit;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using System.Linq;
namespace PMSGSC.App
{
    public partial class frmJobDescription : DevExpress.XtraEditors.XtraForm
    {
        public frmJobDescription(frmMain objMain)
        {
            InitializeComponent();
            jobDescriptionBindingSource.DataSource = JobsDescription_BLL.GetAllJob(frmMain.ship.Ship_ID);
            main = objMain;
            
        }
        frmMain main;
        // Khai báo trạng thái mặc định 
        private Status status = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private JobDescription JobDescription = new JobDescription();
        private Revision objRevision;
        //Hiển thị số thứ tự của gridview
        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        // Sự kiện cập nhật dữ liệu xuống databse
        private void gridView1_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SaveDataToDatabase();
        }
        private void SaveDataToDatabase()
        {
            if (status == Status.New)
            {
                JobDescription.Status = "Draft";
                bool result = JobsDescription_BLL.Insert(JobDescription);
                JobDescription = JobsDescription_BLL.GetNewJobDescription();

                Revision revision = new Revision();
                revision.JobDescription_ID = JobDescription.JobDescription_ID;
                revision.RevisionNumber = 1;
                revision.CreateDate = DateTime.Now.Date;
                revision.Detail = revisionDetail.Text;
                revision.Status = "Draft";
                revision.Title = JobDescription.NameJD;
                revision.CreateBy = "TiNi";
                Revisions_BLL.Insert(revision);
                if (!result)
                {
                    XtraMessageBox.Show("Insert Unsuccess!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                status = Status.Update;
            }

            jobDescriptionBindingSource.DataSource = JobsDescription_BLL.GetAllJob(frmMain.ship.Ship_ID);
        }
        private void DeleteJobDecription(NavigatorButtonClickEventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure you want to delete a JobDescription?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                JobDescription = jobDescriptionBindingSource.Current as JobDescription;

                if (JobsDescription_BLL.IsRelationship(JobDescription))
                    JobsDescription_BLL.Delete(JobDescription);
                else
                {
                    XtraMessageBox.Show("Can't Delete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Handled = true;
                }

                jobDescriptionBindingSource.DataSource = JobsDescription_BLL.GetAllJob(frmMain.ship.Ship_ID);
            }
            else
            {
                e.Handled = true;
            }
        }

        // Sự kiện nhân phím delete sảy ra
        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (XtraMessageBox.Show("Are you sure you want to delete a JobDescription?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    JobDescription = jobDescriptionBindingSource.Current as JobDescription;

                    if (JobsDescription_BLL.IsRelationship(JobDescription))
                        JobsDescription_BLL.Delete(JobDescription);
                    else
                    {
                        XtraMessageBox.Show("Can't Delete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        e.Handled = true;
                    }

                    jobDescriptionBindingSource.DataSource = JobsDescription_BLL.GetAllJob(frmMain.ship.Ship_ID);
                }
                else
                {
                    e.Handled = true;
                }
            }
        }
        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            status = Status.New;

            GridView view = (GridView)sender;
            GridColumn StatusCol = view.Columns["Status"];
            GridColumn IsCheckCol = view.Columns["IsCheck"];
            GridColumn RevisionCol = view.Columns["RevisionNumber"];
            view.SetRowCellValue(e.RowHandle, StatusCol, "Draft");
            view.SetRowCellValue(e.RowHandle, RevisionCol, 1);
            view.SetRowCellValue(e.RowHandle, IsCheckCol, false);
        }
        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = (GridView)sender;
            GridColumn JobDescriptionCodeCol = view.Columns["CodeJD"];
            if (null == view.GetRowCellValue(e.RowHandle, JobDescriptionCodeCol))
            {
                e.Valid = false;
                view.FocusedColumn = JobDescriptionCodeCol;
                e.ErrorText = "Please enter the Job Description Code.";
                view.SetColumnError(JobDescriptionCodeCol, "Job Description Code is not empty");
            }
            JobDescription = jobDescriptionBindingSource.Current as JobDescription;
            JobDescription.Ship_ID = frmMain.ship.Ship_ID;
            if (JobsDescription_BLL.IsExits(JobDescription))
            {
                e.Valid = false;
                view.FocusedColumn = JobDescriptionCodeCol;
                e.ErrorText = "JobDescription Code is exits.";
                view.SetColumnError(JobDescriptionCodeCol, "JobDescription Code is exits");
            }

        }

        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridView1_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl1.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    jobDescriptionBindingSource.DataSource = JobsDescription_BLL.GetAllJob(frmMain.ship.Ship_ID);
                    status = Status.Update;
                }
            }

        }
        // Đặt lại trạng thái update 
        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                status = Status.Update;
            }
        }

        private void jobDescriptionBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            if (JobDescription != null)
            {
                if (ucRichEditControl1.isChange)
                {
                    JobDescription.DetailsJD = ucRichEditControl1.richEditControl1.Text;
                }
            }
            JobDescription = jobDescriptionBindingSource.Current as JobDescription;
            if (JobDescription != null)
            {
                ucRichEditControl1.richEditControl1.Text = JobDescription.DetailsJD;
            }
                
        }

    
        private void gridControl1_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.ButtonType)
            {
                case NavigatorButtonType.Remove:
                    DeleteJobDecription(e);
                    break;
            }
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            GridView view = (GridView)sender;
            Point pt = view.GridControl.PointToClient(Control.MousePosition);
            DoRowDoubleClick(view, pt);
        }

        private void DoRowDoubleClick(GridView view, Point pt)
        {
            GridHitInfo info = view.CalcHitInfo(pt);

            if (info.InRow || info.InRowCell)
            {
                if (info.RowHandle != GridControl.NewItemRowHandle)
                {
                    if (Revisions_BLL.GetCountRevision(JobDescription.JobDescription_ID) > 0)
                    {
                        frmRevisionJob revisionJob = new frmRevisionJob(JobDescription);
                        revisionJob.MdiParent = main;
                        revisionJob.Show();
                    }
                    else
                    {
                        XtraMessageBox.Show("Database is changed !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        jobDescriptionBindingSource.DataSource = JobsDescription_BLL.GetAllJob(frmMain.ship.Ship_ID);
                    }
                }
            }
        }
        private void gridView1_ShowingEditor(object sender, CancelEventArgs e)
        {
            GridView view = sender as GridView;
            GridColumn IsCheckCol = view.Columns["IsCheck"];
            if (!view.IsNewItemRow(view.FocusedRowHandle) && view.FocusedColumn != IsCheckCol)
                e.Cancel = true;
        }

        private void btnSaveAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure you want to upate a JobDescription?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                foreach (JobDescription job in jobDescriptionBindingSource.Cast<JobDescription>().ToList())
                {
                    bool result = JobsDescription_BLL.Update(job);                    
                }
                jobDescriptionBindingSource.DataSource = JobsDescription_BLL.GetAllJob(frmMain.ship.Ship_ID);
            }
        }

        private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            jobDescriptionBindingSource.DataSource = JobsDescription_BLL.GetAllJob(frmMain.ship.Ship_ID);
        }

        private void btnPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            List<JobDescription> workOrder = GetNumberOfJobBeforePrint();
            if (workOrder.Count > 0)
            {
               
            }
        }
        public List<JobDescription> GetNumberOfJobBeforePrint()
        {
            List<JobDescription> jobList = new List<JobDescription>();
            foreach (JobDescription j in jobDescriptionBindingSource.Cast<JobDescription>().ToList())
            {
                if (j.IsCheck.Value)
                    jobList.Add(j);
            }
            return jobList;
        }

        private void IsCheck_CheckedChanged(object sender, EventArgs e)
        {
            JobDescription.IsCheck = bool.Parse(IsCheck.ValueChecked.ToString());
        }

        private void gridControl1_FocusedViewChanged(object sender, ViewFocusEventArgs e)
        {

        }

        private void frmJobDesciption_Click(object sender, EventArgs e)
        {

        }
    }
}